package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.advice.RecordLogAnno;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult findClazz(ClazzQueryParam clazzQueryParam) {

        Page<Clazz> page = new Page<>(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());


        QueryWrapper<Clazz> wrapper = new QueryWrapper<>();
        if (clazzQueryParam.getName() != null && !clazzQueryParam.getName().isEmpty()) {
            wrapper.like("name", clazzQueryParam.getName());
        }


        Page<Clazz> pageResult = clazzMapper.selectPage(page, wrapper);


        for (Clazz clazz : pageResult.getRecords()) {
            if (clazz.getEndDate().isBefore(LocalDate.now())) {
                clazz.setStatus("已结课");
            } else if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开班");
            } else {
                clazz.setStatus("在读中");
            }
        }

        return new PageResult(pageResult.getTotal(), pageResult.getRecords());
    }

    @Override
    @RecordLogAnno
    public void deleteClazz(Integer id) {
        int studentCount = clazzMapper.countStudentsInClazz(id);
        if (studentCount > 0) {
            throw new RuntimeException("班级中存在学生，无法删除");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    @RecordLogAnno
    public void saveClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public List<Clazz> findAllClazzs() {
        return clazzMapper.selectList(null);
    }

    @Override
    public Clazz getClazzById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    @RecordLogAnno
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }
}